
import json
import os
import uuid
from datetime import datetime
import requests
from django.http import JsonResponse
from django.conf import settings
from django.views import View
from PIL import Image
from io import BytesIO


from record.models import Record, RecordSerializer, UserRecord, UserRecordSerializer
from user.models import User

# Create your views here.

class ScanView(View):
    def post(self,request):
        if request.method == 'POST' and request.FILES.get('image'):
            try:
                # ================= 1. 读取图片 =================
                img_file = request.FILES.get('image')

                # 将上传的文件转换为PIL Image对象
                img = Image.open(BytesIO(img_file.read())).convert('RGB')

                # 保存上传的图片到媒体目录
                file_name = img_file.name
                suffix_name = os.path.splitext(file_name)[1]
                new_file_name = datetime.now().strftime('%Y%m%d%H%M%S') + '_' + str(uuid.uuid4())[:8] + suffix_name

                # 确保目录存在
                image_dir = os.path.join(settings.MEDIA_ROOT, "garbage_images")
                os.makedirs(image_dir, exist_ok=True)

                file_path = os.path.join(image_dir, new_file_name)

                # 保存图片
                img_copy = img.copy()
                img_copy.save(file_path)

                # 生成图片的URL路径 (相对路径，不包含域名)
                relative_image_url = os.path.join('media', 'garbage_images', new_file_name).replace('\\', '/')
                print("保存的图片路径:", file_path)
                print("图片URL:", relative_image_url)

                # ================= 2. 调用外部API进行识别 =================
                # 准备要发送的文件
                files = {'image': (new_file_name, open(file_path, 'rb'), img_file.content_type)}
                
                # 发送请求到外部识别API
                response = requests.post('http://39.101.79.51:9960/api/predict/', files=files)
                
                # 检查响应状态
                api_result = response.json()
                print("API响应:", api_result)
                
                if response.status_code != 200 or api_result.get('status') != 'success':
                    return JsonResponse({
                        'code': 500,
                        'message': f'外部识别服务响应错误: {response.text}'
                    })

                # ================= 3. 处理返回结果 =================
                # 构建结果数据
                result_data = {
                    'class_id': api_result.get('class_id'),
                    'predicted_class': api_result.get('predicted_class'),
                    'confidence': api_result.get('confidence'),
                    'probabilities': api_result.get('probabilities', {}),
                    'image_url': relative_image_url  # 添加我们保存的图片URL
                }
                
                return JsonResponse({
                    'code': 200,
                    'data': result_data,
                    'message': '识别成功'
                })

            except Exception as e:
                return JsonResponse({
                    'code': 500,
                    'message': f'识别失败: {str(e)}'
                })

        return JsonResponse({
            'code': 400,
            'message': '请求方法错误或未提供图片'
        })


class SaveView(View):
    def post(self,request):
        try:
            data = json.loads(request.body.decode('utf-8'))
            
            # 获取请求中的数据
            garbage_name = data.get('name')  # 垃圾名称
            garbage_category = data.get('category')  # 垃圾类别
            recycle_method = data.get('recycle_method')  # 处理建议
            image_url = data.get('image', '')  # 垃圾图片URL
            user_id = data.get('user_id')  # 用户ID
            
            print("接收到的图片URL:", image_url)
            
            # 数据验证
            if not garbage_name or not garbage_category or not recycle_method:
                return JsonResponse({
                    'code': 400,
                    'message': '缺少必要参数'
                })
            
            # 验证用户ID是否存在
            if not user_id:
                return JsonResponse({
                    'code': 401,
                    'message': '必须登录才能保存记录'
                })
                
            # 创建Record记录
            record = Record(
                name=garbage_name,
                category=garbage_category,
                recycle_method=recycle_method,
                image=image_url
            )
            record.save()
            user = User.objects.get(id=user_id)
            if not user:
                return JsonResponse({
                    'code': 401,
                    'message': '必须登录才能增加识别次数'
                })
            old_scan_count = user.scanCount
            new_scan_count = old_scan_count + 1
            user.scanCount = new_scan_count
            user.save()
            print("保存的记录:", RecordSerializer(record).data)
            
            # 创建用户与记录的关联
            try:
                user = User.objects.get(id=user_id)
                user_record = UserRecord(user=user, record=record)
                user_record.save()
            except User.DoesNotExist:
                # 用户不存在，删除刚创建的记录
                record.delete()
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })

            # 返回成功响应
            return JsonResponse({
                'code': 200,
                'data': {
                    'record_id': record.id,
                    'record': RecordSerializer(record).data
                },
                'message': '记录保存成功'
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'保存失败: {str(e)}'
            })


class GetListView(View):
    def post(self, request):
        try:
            data = json.loads(request.body.decode('utf-8'))
            user_id = data.get('user_id')
            
            # 验证用户ID是否存在
            if not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '必须提供用户ID'
                })
                
            # 检查用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })
                
            # 获取该用户的所有记录关联
            user_records = UserRecord.objects.filter(user=user)
            record_ids = [ur.record.id for ur in user_records]
            
            # 获取所有关联的记录详情
            records = Record.objects.filter(id__in=record_ids).order_by('-created_time')
            serialized_records = RecordSerializer(records, many=True).data
            
            return JsonResponse({
                'code': 200,
                'data': serialized_records,
                'count': len(serialized_records),
                'message': '获取成功'
            })
            
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'获取记录失败: {str(e)}'
            })


class DeleteRecordView(View):
    def post(self, request):
        try:
            data = json.loads(request.body.decode('utf-8'))
            record_id = data.get('record_id')
            user_id = data.get('user_id')
            
            # 验证必要参数
            if not record_id or not user_id:
                return JsonResponse({
                    'code': 400,
                    'message': '缺少必要参数'
                })
            
            # 检查用户是否存在
            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '用户不存在'
                })
            
            # 检查记录是否存在
            try:
                record = Record.objects.get(id=record_id)
            except Record.DoesNotExist:
                return JsonResponse({
                    'code': 404,
                    'message': '记录不存在'
                })
            
            # 检查记录是否属于该用户
            try:
                user_record = UserRecord.objects.get(user=user, record=record)
            except UserRecord.DoesNotExist:
                return JsonResponse({
                    'code': 403,
                    'message': '无权操作此记录'
                })
            
            # 删除用户记录关联
            user_record.delete()
            
            # 检查是否还有其他用户关联此记录
            if UserRecord.objects.filter(record=record).exists():
                # 还有其他用户关联，不删除记录
                return JsonResponse({
                    'code': 200,
                    'message': '记录关联已删除，但记录保留'
                })
            else:
                # 没有其他用户关联，删除记录
                # 如果记录有关联图片，也可以在这里删除图片文件
                image_path = record.image
                record.delete()
                
                # 如果存在图片且图片路径以 media/garbage_images/ 开头，尝试删除图片文件
                if image_path and image_path.startswith('media/garbage_images/'):
                    try:
                        full_path = os.path.join(settings.MEDIA_ROOT, image_path.replace('media/', '', 1))
                        if os.path.exists(full_path):
                            os.remove(full_path)
                            print(f"已删除图片: {full_path}")
                    except Exception as e:
                        print(f"删除图片失败: {e}")
                
                return JsonResponse({
                    'code': 200,
                    'message': '记录已完全删除'
                })
            
        except Exception as e:
            return JsonResponse({
                'code': 500,
                'message': f'删除失败: {str(e)}'
            })